package com.gnerv.pabu.basic.core.config;

import com.gnerv.pabu.basic.auto.PabuConfigProperties;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * <p>
 * Swagger2配置文件
 * </p>
 *
 * @author Gnerv LiGen
 * @since 2019-10-10
 **/
@Configuration
@EnableSwagger2
public class Swagger2 {

    @Autowired
    PabuConfigProperties pabuConfigProperties;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(pabuConfigProperties.getSwagger().isStatus())
                .apiInfo(apiInfo())
                .select()
                .apis(basePackage(pabuConfigProperties.getSwagger().getPath()))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("基础平台后台接口")
                .version("2.0")
                .build();
    }

    private static Predicate<RequestHandler> basePackage(final String[] basePackages) {
        return input -> declaringClass(input).transform(handlerPackage(basePackages)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String[] basePackages) {
        return input -> {
            // 循环判断匹配
            for (String s : basePackages) {
                boolean isMatch = input.getPackage().getName().startsWith(s);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
}
